/*
 * @Author: your name
 * @Date: 2022-01-26 17:11:28
 * @LastEditTime: 2022-01-27 09:56:42
 * @LastEditors: LAPTOP-L472H14P
 * @Description: In User Settings Edit
 * @FilePath: \react_front_engineer\src\NodeJs\JWT\index.js
 */
const express = require('express')
const app = express()
app.use(express.json())
// 1.引入所需包, 解析和编译
const jsonToken = require('jsonwebtoken')
const expressToekn = require('express-jwt')
// 4.添加解析中间间，将信息返回到req.user中
app.use(
  expressToekn({ secret: 'hand', algorithms: ['HS256'] }).unless({
    path: [/^\/api\//],
  }),
)
// 5.为token添加错误处理中间件
app.use((err,req,res,next)=>{
    console.log(err.name);
    if(err.name === "UnauthorizedError"){
        res.send({masg: "token已过期或不合法"})
    }
})
// 2.定义secret密钥
app.post('/api/login', (req, res) => {
  const secret = 'hand'
  // 3.生成token字符串
  const token = jsonToken.sign({ username: req.body.username, age: 30 }, secret, {
    expiresIn: '30h',
  })
  res.send({
    ...req.body,
    token,
  })
  console.log(req.body)
})
app.get('/test', (req, res) => {
  console.log(req.user)
  res.send({
    ...req.body,
    msg:"请求成功",
  })
})
app.listen('3000')
